// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package rand

import (
	"crypto/rand"
	"io"
	"math/big"
)

// rand provides a simple wrap of "crypto/rand".

// Reader is a global random number source
var Reader io.Reader = &cryptoRandReader{}

type cryptoRandReader struct{}

func (c *cryptoRandReader) Read(b []byte) (int, error) {
	return rand.Read(b)
}

// Int wraps Int63n
func Int() int {
	val := Int63n(int64(int(^uint(0) >> 1)))
	return int(val)
}

// Intn wraps Int63n
func Intn(n int) int {
	if n <= 0 {
		panic("argument to Intn must be positive")
	}
	val := Int63n(int64(n))
	return int(val)
}

// Int63n wraps rand.Int
func Int63n(n int64) int64 {
	if n <= 0 {
		panic("argument to Int63n must be positive")
	}
	val, err := rand.Int(rand.Reader, big.NewInt(n))
	if err != nil {
		panic(err)
	}
	return val.Int64()
}
